//
//  KAInfoExtVC.swift
//  kano
//
//  Created by Frank on 2024/9/9.
//

import Foundation
import SwiftyJSON
import Popover

//MARK: - Member
class KAInfoExtVC: KABaseVC {
    
    lazy var var_dataArray = [KASectionInfo]()
    
    var var_selectGender: String = ""
    var var_selectBirthday: String = ""
    
    var applyModel: KAApply
    var var_pageModel: KAApplyPageElement?
    var var_model: KAPerson = KAPerson()
    
    var var_contactModel: KAContact?
    var var_basicModel: KABasic?
    var var_contactArray: [Dictionary<String, Any>] = []
    
    
    var hasEmailPopover: Bool = false
    
    static let var_itemCellId = "KAApplyInfoCell"
    lazy var var_tableView: UITableView = {
        let var_tableView = UITableView(frame: CGRect(x: 0.0, y: UIDevice.ka_fullNavHeight, width: view.width, height: UIDevice.ka_viewHeight), style: .grouped)
        var_tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        var_tableView.backgroundColor = .colorFFF
        var_tableView.register(KAApplyInfoCell.self, forCellReuseIdentifier: Self.var_itemCellId)
        var_tableView.dataSource = self
        var_tableView.delegate = self
        var_tableView.separatorStyle = .none
        var_tableView.register(KAApplyTitleHeader.self, forHeaderFooterViewReuseIdentifier: "KAApplyTitleHeader")
        var_tableView.register(KAApplySectionFooter.self, forHeaderFooterViewReuseIdentifier: "KAApplySectionFooter")
        var_tableView.tableFooterView = var_tableFooter
        //var_tableView.separatorColor = UIColor(0xffffff, alphaVaule: 0.15)
        return var_tableView
    }()
    
    lazy var var_tableFooter: KAApplyFooter = {
        let var_tableFooter = KAApplyFooter()
        var_tableFooter.var_loginButton.setTitle("Submit", for: .normal)
        var_tableFooter.var_loginButton.addTarget(self, action: #selector(ka_nextBtnClick), for: .touchUpInside)
        return var_tableFooter
    }()
    
    
    var educationList: [KAPickerData] = []
    var jobList: [KAPickerData] = []
    var professionList: [KAPickerData] = []
    var salaryList: [KAPickerData] = []
    var maritalList: [KAPickerData] = []
    var residenceList: [KAPickerData] = []
    var homeStateList: [KAPickerData] = []
    var cityList: [KAPickerData] = []
    var payDayList: [KAPickerData] = []
    var emailList: [KAPickerData] = []
    
    
    init(model: KAApply) {
        applyModel = model
        var_pageModel = model.creditElement?.pageElements?[1]
        
        let dicResult = dealStringToObject(with: model.creditElement?.creditResult) as? [String : Any]
        let submitDic = dicResult?["personinfo"] as? String
        if submitDic != nil {
            let submit = submitDic!.kj.model(KAPerson.self)
            var_model = submit!
        }
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: - circlelife
extension KAInfoExtVC {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let data = KAPageInfo(eleId: "sx_acv_personinfo", path: "\(KAInfoExtVC.self)")
        KAReport.ka_reportWith(type: .page, data: data.kj.JSONObject())
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_configData()
        ka_setUI()
    }
    func ka_configData() {
        let education = KARowInfo(placeHolder: "Please select your highest degree" )
        let educationSec = KASectionInfo(showHeader: true, sectionTitle: "Education", sectionList: [education], type: .education)
        
        let jobStatus = KARowInfo(placeHolder: "Please select your job status")
        let jobStatusSec = KASectionInfo(showHeader: true, sectionTitle: "Job status", sectionList: [jobStatus], type: .jobStatus)
        
        let profession = KARowInfo(placeHolder: "Please select your profession")
        let professionSec = KASectionInfo(showHeader: true, sectionTitle: "Profession", sectionList: [profession], type: .profession)
        
        let salary = KARowInfo(placeHolder: "Please select your salary")
        let salarySec = KASectionInfo(showHeader: true, sectionTitle: "Salary", sectionList: [salary], type: .salary)
        
        let marital = KARowInfo(placeHolder: "Please select your marital status")
        let maritalSec = KASectionInfo(showHeader: true, sectionTitle: "Marital status", sectionList: [marital], type: .marital)
        
        let residence = KARowInfo(placeHolder: "Please select your Type of residence")
        let residenceSec = KASectionInfo(showHeader: true, sectionTitle: "Type of residence", sectionList: [residence], type: .residence)
        
        let home = KARowInfo(placeHolder: "Please select state")
        let homeSec = KASectionInfo(showHeader: true, sectionTitle: "State of home", sectionList: [home], type: .home)
        
        let city = KARowInfo(placeHolder: "Please select city or area")
        let citySec = KASectionInfo(showHeader: false, sectionTitle: "", sectionList: [city], type: .city)
        
        let address = KARowInfo(placeHolder: "Please fill in the detailed block address")
        let addressSec = KASectionInfo(showHeader: true, sectionTitle: "Address", sectionList: [address], type: .address)
        
        let alternate = KARowInfo(placeHolder: "Please use your phone number related to BVN")
        let alternateSec = KASectionInfo(showHeader: true, sectionTitle: "Alternate number(Optional)", sectionList: [alternate], type: .alternate)
        
        let payDay = KARowInfo(placeHolder: "Please select pay day")
        let payDaySec = KASectionInfo(showHeader: true, sectionTitle: "Pay day", sectionList: [payDay], type: .payDay)
        
        let entryDate = KARowInfo(placeHolder: "Please select date of entry")
        let entryDateSec = KASectionInfo(showHeader: true, sectionTitle: "Date of entry", sectionList: [entryDate], type: .entryDate)
        
        let companyPhone = KARowInfo(placeHolder: "Please input company phone")
        let phoneSec = KASectionInfo(showHeader: true, sectionTitle: "Company phone", sectionList: [companyPhone], type: .companyPhone)
        
        let mail = KARowInfo(placeHolder: "Please input your personal mail")
        let mailSection = KASectionInfo(showHeader: true, sectionTitle: "Personal mail", sectionList: [mail], type: .mail)
        
        var_dataArray.append(educationSec)
        var_dataArray.append(jobStatusSec)
        var_dataArray.append(professionSec)
        var_dataArray.append(salarySec)
        var_dataArray.append(maritalSec)
        var_dataArray.append(residenceSec)
        var_dataArray.append(homeSec)
        var_dataArray.append(citySec)
        var_dataArray.append(addressSec)
        var_dataArray.append(alternateSec)
        var_dataArray.append(payDaySec)
        var_dataArray.append(entryDateSec)
        var_dataArray.append(phoneSec)
        var_dataArray.append(mailSection)
    }
    func ka_setUI() {
        view.backgroundColor = .white
        view.addSubview(var_tableView)
        
        ka_showCustomerNavBar(type: .normal)
        var_navBar.var_titleLabel.text = "Obtain credit limit"
        ht_loadPickerList()
    }
}

//MARK: - net
extension KAInfoExtVC {
    //
    @objc func ka_nextBtnClick() {
        if var_model.email.isEmpty || var_model.companyTel.isEmpty || var_model.jobBeginTime.isEmpty || var_model.homeAddressDetail.isEmpty || var_model.educationLevel.label.isEmpty || var_model.jobStatus.label.isEmpty || var_model.job.label.isEmpty || var_model.monthSalary.label.isEmpty || var_model.marriageStatus.label.isEmpty || var_model.residentialType.label.isEmpty || var_model.homeAddressState.label.isEmpty  || var_model.homeAddressRegion.label.isEmpty || var_model.payDay.label.isEmpty {
            view.makeToast("Please complete the information"); return
        }
        if !var_model.companyTel.correctNumber().verifyPhone {
            view.makeToast("The phone format is incorrect"); return
        }
        if !var_model.alternateNum.isEmpty && !var_model.alternateNum.correctNumber().verifyPhone {
            view.makeToast("The phone format is incorrect"); return
        }
        if !var_model.homeAddressDetail.verifyAddress {
            view.makeToast("The address format is incorrect"); return
        }
        if !var_model.email.verifyEmail {
            view.makeToast("The mailbox format is incorrect"); return
        }
        
        let btnInfo = KABtnInfo(eleId: "sx_acb_personinfo_submit", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
        KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        
        var identityInfo = var_basicModel!.kj.JSONObject()
        identityInfo["identityDocumentFrontImage"] = ""
        identityInfo["identityDocumentBackImage"] = ""
        identityInfo["liveImage"] = ""
        
        let personInfo = [
            "educationLevel" : var_model.educationLevel.label,
            "jobStatus" : var_model.jobStatus.label,
            "job" : var_model.job.label,
            "monthSalary" : var_model.monthSalary.label,
            "marriageStatus" : var_model.marriageStatus.label,
            "residentialType" : var_model.residentialType.label,
            "homeAddressState" : var_model.homeAddressState.label,
            "homeAddressRegion" : var_model.homeAddressRegion.label,
            "payDay" : var_model.payDay.label,
            "homeAddressDetail" : var_model.homeAddressDetail,
            "jobBeginTime" : var_model.jobBeginTime,
            "companyTel" : var_model.companyTel,
            "email" : var_model.email,
            "alternateNum" : var_model.alternateNum,
            "whatsapp" : var_model.whatsapp,
            "facebook" : var_model.facebook
        ]
        let data: [String : Any] = [
            "refusalToSubmit" : 0,
            "contactStatus" : "",
            "s3FileType" : "",
            "identityInfo" : identityInfo,
            "contactsDetails" : var_contactArray,
            "persons" : personInfo,
            "licensetypecategory" : "ADVANCE",
            "livenessId" : applyModel.creditElement?.livenessId ?? ""
        ]
        let submitData: [String : Any] = [
            "taskId" : applyModel.creditElement?.pageElements?.first?.taskId ?? "",
            "code" : "20001",
            "lazyLoadingSubmit" : 0,
            "data" : data,
        ]
        let redisCreditDatas: [String : Any] = [
            "idcard" : var_basicModel!.kj.JSONString(),
            "contact" : var_contactModel?.kj.JSONString() ?? "",
            "personinfo" : var_model.kj.JSONString(),
        ]
        let submitDic: [String : Any] = [
            "userGid" : KAUserManager.shared.user.userGid,
            "submissionData" : submitData,
            "creditDataFromRedis" : redisCreditDatas,
        ]
        view.showLoading()
        applyProvider.request(.totalSubmit(submitDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    ApplyResponse<[KAPickerData]>.handleApplyResponse(response.data) { isSuccess, message, response in
                        if !isSuccess {view.hideLoading()}
                        ka_requestResult()
                    }
                } else {
                    view.hideLoading()
                }
            case .failure(let error):
                view.hideLoading()
                print(error.localizedDescription)
            }
        }
    }
    
    func ka_requestResult() {
        let paramDic: [String : Any] = [
            "taskId": var_pageModel!.taskId, "requestCode": "20001"
        ]
        applyProvider.request(.submitStatus(paramDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    guard let responseString = String(data: response.data, encoding: .utf8) else {
                        return
                    }
                    let jsonData = JSON(parseJSON: responseString)
                    guard let dictionary = jsonData.dictionaryObject else {
                        return
                    }
                    guard let data = dictionary["data"] as? [String : Any] else {
                        ka_requestResult()
                        return
                    }
                    guard let code = data["code"] as? String else {
                        return
                    }
                    
                    if code == "80000" {
                        navigationController?.pushViewController(KAApplyResultVC(reviewResult: .reviewing), animated: true)
                    } else {
                        self.view.makeToast(data["message"] as? String)
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    func ht_loadPickerList() {
        view.showLoading()
        let dispatchGroup = DispatchGroup()
        for i in 0..<var_dataArray.count {
            let sectionData = var_dataArray[i]
            let model = var_pageModel?.elements?[i]
            let paramDic: [String : Any] = [
                "taskId" : var_pageModel?.taskId ?? "",
                "fieldId" : model?.fieldId ?? "",
            ]
            dispatchGroup.enter()
            applyProvider.request(.pikerSources(paramDic)) { [self] result in
                switch result {
                case .success(let response):
                    if response.statusCode == 200 {
                        ApplyResponse<[KAPickerData]>.handleApplyResponse(response.data) { isSuccess, message, response in
                            if !isSuccess {}
                            switch sectionData.type {
                            case .education:
                                educationList = (response?.data)!
                            case .jobStatus:
                                jobList = (response?.data)!
                            case .profession:
                                professionList = (response?.data)!
                            case .salary:
                                salaryList = (response?.data)!
                            case .marital:
                                maritalList = (response?.data)!
                            case .residence:
                                residenceList = (response?.data)!
                            case .home:
                                homeStateList = (response?.data)!
                            case .payDay:
                                payDayList = (response?.data)!
                            default: break
                            }
                        }
                    }
                case .failure(let error):
                    print("Error for index \(i): \(error)")
                }
                dispatchGroup.leave()
            }
        }
        dispatchGroup.notify(queue: .main) {
            self.view.hideLoading()
            print("All requests have been completed.")
        }
    }
    
    func ht_loadPickerList(with index: Int) {
        view.showLoading()
        let model = var_pageModel?.elements?[index]
        var paramDic: [String : Any] = [
            "taskId" : var_pageModel?.taskId ?? "",
            "fieldId" : model?.fieldId ?? "",
        ]
        if index == 7 { //parentId
            paramDic["parentId"] = var_model.homeAddressState.value
        }
        applyProvider.request(.pikerSources(paramDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    ApplyResponse<[KAPickerData]>.handleApplyResponse(response.data) { isSuccess, message, response in
                        if !isSuccess {}
                        let sectionData = var_dataArray[index]
                        
                        guard let sources = dealPickerData(dataArray: (response?.data)!, index: index) else { return }
                        KAPickerView.ka_showStringPicker(title: sectionData.sectionTitle, dataSources: sources, selectValue: sources.first) { [self] selectValue in
                            if let index = sources.firstIndex(of: selectValue) {
                                
                                switch sectionData.type {
                                case .education:
                                    educationList = (response?.data)!
                                    mapCellModel(cellModel: &var_model.educationLevel, pickerModel: educationList[index])
                                case .jobStatus:
                                    jobList = (response?.data)!
                                    mapCellModel(cellModel: &var_model.jobStatus, pickerModel: jobList[index])
                                case .profession:
                                    professionList = (response?.data)!
                                    mapCellModel(cellModel: &var_model.job, pickerModel: professionList[index])
                                case .salary:
                                    salaryList = (response?.data)!
                                    mapCellModel(cellModel: &var_model.monthSalary, pickerModel: salaryList[index])
                                case .marital:
                                    maritalList = (response?.data)!
                                    mapCellModel(cellModel: &var_model.marriageStatus, pickerModel: maritalList[index])
                                case .residence:
                                    residenceList = (response?.data)!
                                    mapCellModel(cellModel: &var_model.residentialType, pickerModel: residenceList[index])
                                case .home:
                                    homeStateList = (response?.data)!
                                    mapCellModel(cellModel: &var_model.homeAddressState, pickerModel: homeStateList[index])
                                case .city:
                                    cityList = (response?.data)!
                                    mapCellModel(cellModel: &var_model.homeAddressRegion, pickerModel: cityList[index])
                                case .payDay:
                                    payDayList = (response?.data)!
                                    mapCellModel(cellModel: &var_model.payDay, pickerModel: payDayList[index])
                                default: break
                                }
                                var_tableView.reloadData()
                            }
                        }
                    }
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}

//MARK: - UITableViewDelegate
extension KAInfoExtVC : UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        var_dataArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionData = var_dataArray[section]
        return sectionData.sectionList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let sectionData = var_dataArray[indexPath.section]
        let rowData = sectionData.sectionList[indexPath.row]
        
        let var_cell: KAApplyInfoCell = KAApplyInfoCell.ka_cell(for: tableView)
        var_cell.var_type = sectionData.type
        var_cell.contentTF.text = ""
        var_cell.contentTF.placeholder = rowData.placeHolder
        switch sectionData.type {
        case .education:
            var_cell.contentTF.text = var_model.educationLevel.label
        case .jobStatus:
            var_cell.contentTF.text = var_model.jobStatus.label
        case .profession:
            var_cell.contentTF.text = var_model.job.label
        case .salary:
            var_cell.contentTF.text = var_model.monthSalary.label
        case .marital:
            var_cell.contentTF.text = var_model.marriageStatus.label
        case .residence:
            var_cell.contentTF.text = var_model.residentialType.label
        case .home:
            var_cell.contentTF.text = var_model.homeAddressState.label
        case .city:
            var_cell.contentTF.text = var_model.homeAddressRegion.label
        case .address:
            var_cell.contentTF.text = var_model.homeAddressDetail
            var_cell.contentTF.keyboardType = .default
            var_cell.editingHandle = { [self] cell, content in
                var_model.homeAddressDetail = content
            }
            var_cell.tfInfo = rowData.tfInfo;
            var_cell.editDidEndHandle = { cell, tfInfo in
                tfInfo.eleId = "sx_aci_personinfo_home_details"
                tfInfo.pageId = "sx_acv_personinfo"
                rowData.tfInfo = tfInfo
                KAReport.ka_reportWith(type: .tf, data: tfInfo.kj.JSONObject())
            }
        case .alternate:
            var_cell.contentTF.text = var_model.alternateNum
            var_cell.contentTF.keyboardType = .numberPad
            var_cell.editingHandle = { [self] cell, content in
                if content.count > 11 {
                    cell.contentTF.text = String(content.prefix(11))
                }
                var_model.alternateNum = cell.contentTF.text!
            }
            var_cell.tfInfo = rowData.tfInfo;
            var_cell.editDidEndHandle = { cell, tfInfo in
                tfInfo.eleId = "sx_aci_personinfo_otherphone"
                tfInfo.pageId = "sx_acv_personinfo"
                rowData.tfInfo = tfInfo
                KAReport.ka_reportWith(type: .tf, data: tfInfo.kj.JSONObject())
            }
        case .payDay:
            var_cell.contentTF.text = var_model.payDay.label
        case .entryDate:
            var_cell.contentTF.text = var_model.jobBeginTime
        case .companyPhone:
            var_cell.contentTF.text = var_model.companyTel
            var_cell.contentTF.keyboardType = .phonePad
            var_cell.editingHandle = { [self] cell, content in
                if content.count > 11 {
                    cell.contentTF.text = String(content.prefix(11))
                }
                var_model.companyTel = cell.contentTF.text!
            }
            var_cell.tfInfo = rowData.tfInfo;
            var_cell.editDidEndHandle = { cell, tfInfo in
                tfInfo.eleId = "sx_aci_company_phone"
                tfInfo.pageId = "sx_acv_personinfo"
                rowData.tfInfo = tfInfo
                KAReport.ka_reportWith(type: .tf, data: tfInfo.kj.JSONObject())
            }
        case .mail:
            var_cell.contentTF.text = var_model.email
            var_cell.contentTF.keyboardType = .emailAddress
            var_cell.editingHandle = { [self] cell, content in
                var_model.email = content
            }
            var_cell.editingChanged = { [self] cell, content in
                if content.contains("@") { showEmailList(with: var_cell) }
            }
            var_cell.tfInfo = rowData.tfInfo;
            var_cell.editDidEndHandle = { cell, tfInfo in
                tfInfo.eleId = "sx_aci_personinfo_email"
                tfInfo.pageId = "sx_acv_personinfo"
                rowData.tfInfo = tfInfo
                KAReport.ka_reportWith(type: .tf, data: tfInfo.kj.JSONObject())
            }
        default: break
        }
        return var_cell
    }
    
    func showEmailList(with cell: KAApplyInfoCell) {
        if hasEmailPopover { return }
        hasEmailPopover = true
        let options: [PopoverOption] = [.type(.auto), .cornerRadius(8), .animationIn(0.3), .blackOverlayColor(.clear), .arrowSize(CGSize.zero), .dismissOnBlackOverlayTap(true)]
        let popover = Popover(options: options, showHandler: nil) { [self] in
            hasEmailPopover = false
        }
        let aView = KAEmailView(frame: CGRect(x: 0, y: 0, width: view.frame.width - kscale(40), height: 200)) { [self] selectValue in
            cell.contentTF.text = (cell.contentTF.text ?? "") + selectValue
            var_model.email = cell.contentTF.text ?? ""
            popover.dismiss()
            hasEmailPopover = false
        }
        popover.show(aView, fromView: cell)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return kscale(50.0)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sectionData = var_dataArray[section]
        if sectionData.type == .city {
            return UIView()
        }
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "KAApplyTitleHeader") as! KAApplyTitleHeader
        header.titleLabel.text = sectionData.sectionTitle
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        let sectionData = var_dataArray[section]
        if sectionData.type == .city {
            return .leastNonzeroMagnitude
        }
        return kscale(30)
    }
    
//    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//        if section == 0 {
//            let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: "KAApplySectionFooter") as! KAApplySectionFooter
//            return footer
//        }
//        return UIView()
//    }
//    
//    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
//        if section == 0 {
//            return kscale(80)
//        }
//        return .leastNormalMagnitude
//    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.endEditing(true)
        let sectionData = var_dataArray[indexPath.section]
        
        switch sectionData.type {
        case .education:
            let btnInfo = KABtnInfo(eleId: "sx_acb_personinfo_education", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            
            guard let sources = dealPickerData(dataArray: educationList, index: indexPath.section) else { return }
            KAPickerView.ka_showStringPicker(title: sectionData.sectionTitle, dataSources: sources, selectValue: sources.first) { [self] selectValue in
                if let index = sources.firstIndex(of: selectValue) {
                    mapCellModel(cellModel: &var_model.educationLevel, pickerModel: educationList[index])
                    tableView.reloadData()
                }
            }
        case .jobStatus:
            let btnInfo = KABtnInfo(eleId: "sx_acb_job_status", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            
            guard let sources = dealPickerData(dataArray: jobList, index: indexPath.section) else { return }
            KAPickerView.ka_showStringPicker(title: sectionData.sectionTitle, dataSources: sources, selectValue: sources.first) { [self] selectValue in
                if let index = sources.firstIndex(of: selectValue) {
                    mapCellModel(cellModel: &var_model.jobStatus, pickerModel: jobList[index])
                    tableView.reloadData()
                }
            }
        case .profession:
            let btnInfo = KABtnInfo(eleId: "sx_acb_person_occupation", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            
            guard let sources = dealPickerData(dataArray: professionList, index: indexPath.section) else { return }
            KAPickerView.ka_showStringPicker(title: sectionData.sectionTitle, dataSources: sources, selectValue: sources.first) { [self] selectValue in
                if let index = sources.firstIndex(of: selectValue) {
                    mapCellModel(cellModel: &var_model.job, pickerModel: professionList[index])
                    tableView.reloadData()
                }
            }
        case .salary:
            let btnInfo = KABtnInfo(eleId: "sx_acb_personinfo_monthIncome", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            
            guard let sources = dealPickerData(dataArray: salaryList, index: indexPath.section) else { return }
            KAPickerView.ka_showStringPicker(title: sectionData.sectionTitle, dataSources: sources, selectValue: sources.first) { [self] selectValue in
                if let index = sources.firstIndex(of: selectValue) {
                    mapCellModel(cellModel: &var_model.monthSalary, pickerModel: salaryList[index])
                    tableView.reloadData()
                }
            }
        case .marital:
            let btnInfo = KABtnInfo(eleId: "sx_acb_personinfo_marriage", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            
            guard let sources = dealPickerData(dataArray: maritalList, index: indexPath.section) else { return }
            KAPickerView.ka_showStringPicker(title: sectionData.sectionTitle, dataSources: sources, selectValue: sources.first) { [self] selectValue in
                if let index = sources.firstIndex(of: selectValue) {
                    mapCellModel(cellModel: &var_model.marriageStatus, pickerModel: maritalList[index])
                    tableView.reloadData()
                }
            }
        case .residence:
            let btnInfo = KABtnInfo(eleId: "sx_acb_personinfo_houseowner", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            
            guard let sources = dealPickerData(dataArray: residenceList, index: indexPath.section) else { return }
            KAPickerView.ka_showStringPicker(title: sectionData.sectionTitle, dataSources: sources, selectValue: sources.first) { [self] selectValue in
                if let index = sources.firstIndex(of: selectValue) {
                    mapCellModel(cellModel: &var_model.residentialType, pickerModel: residenceList[index])
                    tableView.reloadData()
                }
            }
        case .home:
            let btnInfo = KABtnInfo(eleId: "sx_acb_personinfo_home_province", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            
            guard let sources = dealPickerData(dataArray: homeStateList, index: indexPath.section) else { return }
            KAPickerView.ka_showStringPicker(title: sectionData.sectionTitle, dataSources: sources, selectValue: sources.first) { [self] selectValue in
                if let index = sources.firstIndex(of: selectValue) {
                    mapCellModel(cellModel: &var_model.homeAddressState, pickerModel: homeStateList[index])
                    //重新选择一级地区，二级选择框需被清空
                    var_model.homeAddressRegion = KAApplyRowInfo()
                    cityList.removeAll()
                    tableView.reloadData()
                }
            }
        case .city:
            if var_model.homeAddressState.label.isEmpty {
                view.makeToast("Please select State of home first")
                return
            }
            let btnInfo = KABtnInfo(eleId: "sx_acb_personinfo_home_city", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            
            guard let sources = dealPickerData(dataArray: cityList, index: indexPath.section) else { return }
            //            ht_loadPickerList(with: indexPath.section)
            KAPickerView.ka_showStringPicker(title: sectionData.sectionTitle, dataSources: sources, selectValue: sources.first) { [self] selectValue in
                if let index = sources.firstIndex(of: selectValue) {
                    mapCellModel(cellModel: &var_model.homeAddressRegion, pickerModel: cityList[index])
                    tableView.reloadData()
                }
            }
        case .payDay:
            let btnInfo = KABtnInfo(eleId: "sx_acb_salary_date_time", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            
            guard let sources = dealPickerData(dataArray: payDayList, index: indexPath.section) else { return }
            KAPickerView.ka_showStringPicker(title: sectionData.sectionTitle, dataSources: sources, selectValue: sources.first) { [self] selectValue in
                if let index = sources.firstIndex(of: selectValue) {
                    mapCellModel(cellModel: &var_model.payDay, pickerModel: payDayList[index])
                    tableView.reloadData()
                }
            }
        case .entryDate:
            let btnInfo = KABtnInfo(eleId: "sx_acb_company_entry_time", pageId: "sx_acv_personinfo", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            
            KAPickerView.ka_showDatePicker(title: "Date of entry", pickerMode: .YMD, minDate: Date.ka_date(from: "01/01/1953", format: applyFormat), maxDate: Date(), selectDate: Date.ka_date(from: var_model.jobBeginTime, format: applyFormat)) { [self] selectDate, selectValue in
                let dateStr = Date.ka_string(with: selectDate, format: applyFormat)
                var_model.jobBeginTime = dateStr
                tableView.reloadData()
            }
        default: break
        }
    }
    
    func mapCellModel(cellModel: inout KAApplyRowInfo, pickerModel: KAPickerData) {
        cellModel.value = pickerModel.id
        cellModel.parentId = 0
        cellModel.label = pickerModel.value
        cellModel.report = pickerModel.report
    }
    
    func dealPickerData(dataArray: [KAPickerData], index: Int) -> [String]? {
        guard !dataArray.isEmpty else {
            ht_loadPickerList(with: index)
            return nil
        }
        let arrM = dataArray.map { $0.value }
        return arrM
    }
    
//    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        view.endEditing(true)
//    }
//    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        view.endEditing(true)
//    }
}
